package com.hxbd.gxsec_data.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true,jsr250Enabled = true,securedEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("admin")
                .password(bCryptPasswordEncoder().encode("123"))
                .roles("admin");
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().mvcMatchers("/css/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                    .cors()
                    .and()
                    .formLogin()
                    .loginPage("/loginPage")
                    .loginProcessingUrl("/dologin")
                    .successForwardUrl("/gotoIndex")
                    .failureForwardUrl("/faile")
                    .permitAll()
                    .and()
                    .sessionManagement()
                    .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
                    .maximumSessions(1)
                  //.maxSessionsPreventsLogin(true) //如果存在登陆，阻止另一个登陆
                    .expiredUrl("/expireSesson");
            http.authorizeRequests()
                    .antMatchers("/getAllResource"
                                            ,"/getNewsByname"
                                            ,"/getAllNews"
                                            ,"/countTheNumberOfPageVisits"
                                            ,"/searchResource").permitAll()
                    .anyRequest()
                    .authenticated();
            http.headers()
                    .frameOptions()
                    .sameOrigin(); //允许ifram标签嵌套

    }
}
